package utils

// 第三方服务

import (
	"apis/global"
	"errors"
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"go.uber.org/zap"
	"time"
)

// 颁发token
func CreatJwt(username string) string {
	mySigningKey := []byte(global.ApiServer.Jsk)

	// Create the Claims
	claims := &jwt.RegisteredClaims{
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute * 30)), //过期时间
		Issuer:    "test",                                               //颁发者
		ID:        username,
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(mySigningKey)
	if err != nil {
		zap.S().Error("token生成string失败", err)
		return ""
	}
	return ss
}

// 验证token
func ParseJwt(tokenString string) (bool, string) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(global.ApiServer.Jsk), nil
	})

	//获取用户名
	str := fmt.Sprintf("%s", token.Claims.(jwt.MapClaims)["jti"])
	switch {
	case token.Valid:
		//fmt.Println("You look nice today")
		return true, str
	case errors.Is(err, jwt.ErrTokenMalformed):
		//fmt.Println("That's not even a token")
		//JWT 格式错误
		return false, ""
	case errors.Is(err, jwt.ErrTokenSignatureInvalid):
		// Invalid signature
		//fmt.Println("Invalid signature")
		//JWT 的签名无效
		return false, ""
	case errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet):
		// Token is either expired or not active yet
		//fmt.Println("Timing is everything")
		// JWT 已经过期或尚未生效
		return false, ""
	default:
		//fmt.Println("Couldn't handle this token:", err)
		//其他无法处理的错误
		return false, ""
	}
}
